﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using IHISCETeim.BLL;
using IHISCETeim.Library;
using IHISCETeim.Model;
using System.Configuration;
using System.Data;
using System.Text;
using System.IO;
using Newtonsoft.Json;
using System.Net;

namespace IHISCETeim.Web.AgentSys
{
    /// <summary>
    /// ajaxDone 的摘要说明
    /// </summary>
    public class ajaxDone : IHttpHandler
    {
        public enum ajaxmethod {
            /// <summary>
            /// 根据机号获取保修卡信息
            /// </summary>
            getuwarrantycard,
            /// <summary>
            /// 根据品情号获取品情信息
            /// </summary>
            getagnetqlty,
            /// <summary>
            /// 获取快递信息
            /// </summary>
            getkuaidiinfo,
            /// <summary>
            /// 删除保外配件折扣申请
            /// </summary>
            deleteagentpartorder
        }

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";

            string method = context.Request["ajaxmethod"];
             ajaxmethod xmethod = (ajaxmethod)Enum.Parse(typeof(ajaxmethod), method.Trim().ToLower());
            string temp="";
            switch (xmethod)
            {
                case ajaxmethod.getuwarrantycard:
                    temp = getUWarrantyCard();
                    break;
                case ajaxmethod.getagnetqlty:
                    temp = getagnetqlty();
                    break;
                case ajaxmethod.getkuaidiinfo:
                    temp = getkuaidiinfo();
                    break;
                case ajaxmethod.deleteagentpartorder:
                    temp = deleteagentpartorder();
                    break;
            }
            context.Response.Write(temp);
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        #region 操作JSON
        public enum callbackType
        {
            forward,
            closeCurrent
        }
        /// <summary>
        /// 输入操作JOSN
        /// </summary>
        /// <param name="statusCode">200表示成功,300表示失败</param>
        /// <param name="message">操作提示消息</param>
        /// <param name="navTabId">服务器转回navTabId可以把那个navTab标记为reloadFlag=1, 下次切换到那个navTab时会重新载入内容</param>
        /// <param name="callbackType">callbackType如果是closeCurrent就会关闭当前tab,只有callbackType="forward"时需要forwardUrl值</param>
        /// <param name="forwardUrl">重新加的页面路径</param>
        /// <returns></returns>
        private string ResponseOpJson(string statusCode, string message, string navTabId, callbackType callbackType, string forwardUrl)
        {
            // string jsontemp = "{{\"statusCode\":\"200\",\"message\":\"操作成功\",\"navTabId\":\"\",\"callbackType\":\"forward\",\"forwardUrl\":\"sysbasic/omeunlist.aspx\"}}";
            string jsontemp = "{{\"statusCode\":\"{0}\",\"message\":\"{1}\",\"navTabId\":\"{2}\",\"callbackType\":\"{3}\",\"forwardUrl\":\"{4}\"}}";
            return string.Format(jsontemp, statusCode, message, navTabId, callbackType.ToString(), forwardUrl);
        }

        private string SuccessJson(string message, string navTabId, string forwardUrl)
        {
            return ResponseOpJson("200", message, navTabId, callbackType.forward, forwardUrl);
        }
        private string SuccessJson(string message, string forwardUrl)
        {
            return ResponseOpJson("200", message, "", callbackType.forward, forwardUrl);
        }
        private string SuccessJson(string message)
        {
            return ResponseOpJson("200", message, "", callbackType.closeCurrent, "");
        }

        private string ErrorJson(string message, string navTabId, string forwardUrl)
        {
            return ResponseOpJson("300", message, navTabId, callbackType.forward, forwardUrl);
        }
        private string ErrorJson(string message, string forwardUrl)
        {
            return ResponseOpJson("300", message, "", callbackType.forward, forwardUrl);
        }
        private string ErrorJson(string message)
        {
            return ResponseOpJson("300", message, "", callbackType.closeCurrent, "");
        }
        #endregion

        #region 页面参数获取
        protected T GetRequestValue<T>(string name)
        {
            return HttpContext.Current.Request.GetRequestValue<T>(name);
        }

        protected T GetRequestValue<T>(string name, bool useDefValue, T defValue)
        {
            return HttpContext.Current.Request.GetRequestValue<T>(name, useDefValue, defValue);
        }
        protected T GetRequestValue<T>(string name, T defValue)
        {
            return HttpContext.Current.Request.GetRequestValue<T>(name, true, defValue);
        }
        #endregion

        #region 获取保修卡信息
        /// <summary>
        /// 获取保修卡信息
        /// </summary>
        /// <returns></returns>
        private string getUWarrantyCard()
        {
            int UserId = OUserController.CurrentUser.UserId;// GetRequestValue<int>("userid", 0);//20160728添加对经销商认证
            string SerialNumber = GetRequestValue<string>("SerialNumber", "");
            UWarrantyCardInfo obj = UWarrantyCardController.GetBySerialNumber(SerialNumber);
            obj.IntoSpecial = GetDefaultIntoSpecial(obj.IntoSpecial);
            //多名称经销商处理
            DataTable dt = OUserController.OUserMutlCmp_GetListByUserId(UserId);
            OUserInfo objuser = OUserController.GetById(UserId);
            bool haveAgent = false;
            if (objuser.Department == obj.AgentName)
                haveAgent = true;
            if (!haveAgent)
            {
                if (dt.Rows.Count > 0)
                {
                    foreach (DataRow dr in dt.Rows)
                    {
                        if (dr["AgentName"].ToString().Trim() == obj.AgentName)
                            haveAgent = true;
                    }
                }
            }
            if (haveAgent)
                return JsonConvert.SerializeObject(obj);
            else
                return JsonConvert.SerializeObject(new UWarrantyCardInfo() { UWCID = 0});
        }

        private static Dictionary<string, string> _IntoSpecialList = null;
        /// <summary>
        /// 特别附件及规格 ,与机器保修卡上的数据对接
        /// </summary>
        public static Dictionary<string, string> IntoSpecialList
        {
            get
            {
                if (_IntoSpecialList == null)
                {
                    //  机器保修卡数据     品情数据
                    _IntoSpecialList = new Dictionary<string, string>();
                    _IntoSpecialList.Add("标准式样", "标准规格");
                    _IntoSpecialList.Add("带破碎管路", "破碎管路");
                    _IntoSpecialList.Add("加长臂", "加长臂");
                    _IntoSpecialList.Add("加宽铲斗", "加宽铲斗");
                    _IntoSpecialList.Add("其他", "其他");
                }
                return _IntoSpecialList;
            }
        }
        /// <summary>
        /// 获取与机器保修卡上对应的数据
        /// </summary>
        /// <param name="uwIntoSpecial"></param>
        /// <returns></returns>
        public static string GetDefaultIntoSpecial(string uwIntoSpecial)
        {
            uwIntoSpecial = string.IsNullOrEmpty(uwIntoSpecial) ? "" : uwIntoSpecial;
            if (IntoSpecialList.ContainsKey(uwIntoSpecial))
            {
                return IntoSpecialList[uwIntoSpecial];
            }
            return "标准规格";
        }

        /// <summary>
        /// 根据品情号获取品情信息
        /// </summary>
        /// <returns></returns>
        private string getagnetqlty()
        {
            string ClaimsNumber = GetRequestValue<string>("ClaimsNumber", "");

            AgentQltyInfo obj= AgentQltyController.GetByClaimsNumber(ClaimsNumber);
            return JsonConvert.SerializeObject(obj);
        }

        private string getkuaidiinfo()
        {
            string ApiKey = "e6c89f41245855b8";//请把XXXXXX修改成您在快递100网站申请的APIKey
            string expno = GetRequestValue<string>("data","");
            string typeCom = GetRequestValue<string>("com","");
            string nu = GetRequestValue<string>("nu","");
            string powered = "快递数据由: <a href=\"http://www.kuaidi100.com/?refer=hishop\" target=\"_blank\">快递100</a> 提供";

            //1.先根据提供的COM 获取公司信息，
            string _com = typeCom.Length > 2 ? typeCom.Substring(0, 2) : typeCom;
            DataTable list =SKuaiDi100Controller.GetAll();
            DataTable rsv = list.Select(string.Format("kuaidicom like '{0}%'", _com)).CopyToDataTable();
            if (rsv.Rows.Count > 0)
            {
                typeCom = rsv.Rows[0]["kuaidinu"].ToString();
            }
            else
            {
                return "不存在此快递/物流公司";
            }

            string apiurl = "http://api.kuaidi100.com/api?id=" + ApiKey + "&com=" + typeCom + "&nu=" + nu + "&show=2&muti=1&order=asc";
            //Response.Write (apiurl);

            WebRequest request = WebRequest.Create(@apiurl);
            WebResponse response = request.GetResponse();
            Stream stream = response.GetResponseStream();
            Encoding encode = Encoding.UTF8;
            StreamReader reader = new StreamReader(stream, encode);
            string detail = reader.ReadToEnd();

            return (detail + "<br/>找不到相关物流信息?请到相应物流公司官网查询.<br/>" + powered);

        }
        #endregion

        private string deleteagentpartorder()
        {
            int OrderId = GetRequestValue<int>("OrderId", 0);

           // AddDeleteLog("AgentPartOrder", OrderId);

            bool r = AgentPartOrderController.Delete(OrderId);
            if (r)
                return SuccessJson("已成功删除", "AgentPartOrderList", "PWMgr/AgentPartOrderList.aspx");
            else
                return ErrorJson("删除失败<br/>" + r, "AgentPartOrderList", "PWMgr/AgentPartOrderList.aspx");
        }
    }
}